import chalk from 'chalk';

export class ProgressBar {
  constructor(total, label = '') {
    this.total = total;
    this.current = 0;
    this.label = label;
    this.width = 30;
    this.startTime = Date.now();
  }

  update(current) {
    this.current = current;
    this.render();
  }

  render() {
    const percentage = Math.min(this.current / this.total, 1);
    const filledWidth = Math.round(this.width * percentage);
    const emptyWidth = this.width - filledWidth;

    const bar =
      chalk.green('█'.repeat(filledWidth)) + chalk.gray('░'.repeat(emptyWidth));
    const percentText = (percentage * 100).toFixed(1);
    const sizeText = this.formatBytes(this.current) + ' / ' + this.formatBytes(this.total);
    const speedText = this.calculateSpeed();
    const etaText = this.calculateETA();

    process.stdout.write(
      `\r${this.label} [${bar}] ${percentText}% ${sizeText} ${speedText} ETA: ${etaText}`
    );
  }

  complete() {
    const elapsedTime = ((Date.now() - this.startTime) / 1000).toFixed(2);
    this.render();
    console.log(
      `\n${chalk.green('✓')} 完成 (用时: ${elapsedTime}秒)\n`
    );
  }

  formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
  }

  calculateSpeed() {
    const elapsedSeconds = (Date.now() - this.startTime) / 1000;
    if (elapsedSeconds === 0) return '0 B/s';
    const speed = this.current / elapsedSeconds;
    return this.formatBytes(speed) + '/s';
  }

  calculateETA() {
    const elapsedSeconds = (Date.now() - this.startTime) / 1000;
    const speed = this.current / elapsedSeconds;
    if (speed === 0) return '--:--';
    const remainingSeconds = (this.total - this.current) / speed;
    const minutes = Math.floor(remainingSeconds / 60);
    const seconds = Math.floor(remainingSeconds % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  }
}
